//
//  BZOAuthViewController.swift
//  weibo
//
//  Created by zzx on 2017/7/30.
//  Copyright © 2017年 zzx. All rights reserved.
//

import UIKit
import SVProgressHUD


let AppKey = "3153577693"

let Redirect_uri = "http://www.sina.com"

let AppSecret = "a371720f69a32a613f992242ee7f748e"

class BZOAuthViewController: UIViewController {
    
    
    private lazy var webView: UIWebView = UIWebView()
    

    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        
        setupNavigation()
        
        loadLogin()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    private func setupNavigation() {
        
        //左侧的导航栏
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        
        //设置标题
        navigationItem.title = "微博登陆"
        
        //设置右侧的导航栏
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
        
        
        
    }
    
   
    
    
    //MARK:- 加载第三方登陆
    func loadLogin() {
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_uri)"
        
        let url = URL(string: urlStr)
        
        webView.loadRequest(URLRequest(url: url!))
        
        
    }
    
    
    //MARK:- 取消操作
    @objc private func cancelAction() {
        
        self.dismiss(animated: true, completion: nil)
        
        
        
    }
    
    //MARK:- 自动填充操作
    @objc private func autoFillAction() {
        
         webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = 'zhangzixiang08@sina.com';document.getElementById('passwd').value = 'zzx110110';document.getElementById('passwd').focus();")
        
        
    }

}

extension BZOAuthViewController: UIWebViewDelegate{
    //将要加载网络请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if request.url?.absoluteString.hasPrefix(Redirect_uri) == true {
            //代码执行到此,表示以授权回调地址开头
            //query表示后面的参数
            if let query = request.url?.query, query.hasPrefix("code=") {
                
                let code = query.substring(from: "code=".endIndex)
                
                BZUserAccountViewModel.sharedViewModel.requestAccessToken(code: code, callBack: { (isSuccess: Bool) in
                    
                    if isSuccess {
                    
                        print("登陆成功")
                        
                        self.dismiss(animated: false, completion: { 
                            NotificationCenter.default.post(name:NSNotification.Name(SwitchRootVCNotificationName), object: self)
                        })
                    
                    
                    }else{
                        
                        print("登陆失败")
                        
                    }
                    
                    
                    
                })
                
            }else{
                
                //取消授权
                self.dismiss(animated: true, completion: nil)
            
            }
            
            return false
            
        }
        
        //运行加载这次请求地址
        return true
        
    }
    
    //已经开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        print("error")
        SVProgressHUD.dismiss()
        
    }
    
    
}
